var app=angular.module('starter.controllers', ['ionic']);

/* 产品列表 @alexlee */
app.controller('ProductIndexController', function($scope, $http, $state, $ionicLoading,$ionicViewSwitcher,$location) {
  $ionicLoading.show({template: '<ion-spinner class="light"></ion-spinner>'});
  $http.get(window.localStorage.base_url+'/app/product/getRecommandProduct').success(function(req){
    $ionicLoading.hide();
    if(req.code=='0'){console.log(req);
      $scope.recommend = req.product;
    }else{
      console.log(req);
    }
  }).error(function(res){
    $ionicLoading.hide();
    console.log(res);
  })

  $scope.toproduct = function () {
    window.localStorage.backtoproductindex = "backtoproductindex";
    $ionicViewSwitcher.nextDirection('forward');
    $state.go('product-detail',{id:$scope.recommend.id});
  };
})

/*
loginx 产品购买跳转登录 返回 @alexlee
*/
.controller('LoginxController',function($scope, $state, $stateParams, $ionicNavBarDelegate, $ionicLoading,$ionicPopup, $location, $ionicHistory, $http, $httpParamSerializer, userService){
  $scope.longindata = {};

  $scope.submit = function(){
    $ionicLoading.show();
    $http.get(window.localStorage.base_url+'/app/member/login?'+$httpParamSerializer($scope.longindata))
    .success(function(req){
      $ionicLoading.hide();
      if(req.code=='0'){
        if(window.localStorage){
          userService.setLogin($scope.longindata.phone,req.token,req.member.id);
          $ionicHistory.goBack();
          //$location.path('/web/user/index');
        }else{
             alert('This browser does NOT support localStorage');
        }
      }else{
        console.log(req);
        $ionicPopup.alert({title: req.msg, okText:'确定'});
      }
    }).error(function(res){
      $ionicLoading.hide();
      console.log(res);
    });
  }

  $scope.register = function() {
    $location.path('/user/register');
  };

  //直接返回 清除跳转下一步
  $scope.myGoBack = function(){
    console.log('myGoBack');
    var topage = window.localStorage.loginx;
    if (topage == "topay" || topage == "totzfx" || topage == "tofeedback" || topage == "toshare"){
      window.localStorage.removeItem('loginx');
      $ionicHistory.goBack();
    }  
  }

})

/* 产品列表 @alexlee */
.controller('ProductsController', function($scope, $state, $ionicLoading, $location, $stateParams, productsService, _) {
  switch($stateParams.moduleId){
    case '0':
      $scope.title = "定期理财";
      break;    
    case '1':
      $scope.title = "灵活理财";
      break;   
    case '2':
      $scope.title = "新手专享";
      break;
  }
  //$ionicLoading.show();
  productsService.get($stateParams.moduleId).then(function(result){
    //console.log('products get successed');
    $scope.products = result.products;//console.log($scope.products);
    angular.forEach($scope.products,function(value){
      if(value.finishPer > 100){
        value.finishPer =100; //大于100,超卖违规
      }
    });
  },function(){
    console.log('products get error');    
  });
  $scope.notfinish = function (item) {
    return item.finishPer != 100;
  };
})

/* 产品详情 @alexlee */
.controller('ProductDetailController', function($scope, $http, $ionicLoading, $state, $ionicHistory,$ionicViewSwitcher,$location, $timeout, $stateParams, $ionicPopup, $httpParamSerializer) {
  var topay = window.localStorage.loginx;
  if (topay == "topay"){
    window.localStorage.removeItem('loginx');
    $ionicLoading.show({
      template: '<ion-spinner class="light"></ion-spinner>',
      delay:500,
      hideOnStateChange:true
    });
    $timeout(function() {
      $state.go('pay-index',{id:$scope.product.id});
    }, 1500);
  }
  $scope.myGoBack = function(){
    if (window.localStorage.backtoproductindex == "backtoproductindex"){
      window.localStorage.removeItem('backtoproductindex');
      $ionicViewSwitcher.nextDirection('back');
      $state.go('web.product-index',{});
    }else{
      console.log(1111);
      $ionicHistory.goBack();
    }
  }

  $http({
    method:'get',
    url: window.localStorage.base_url+'/app/product/get?productId='+$stateParams.id
  }).success(function(data,status,headers,config){
    //console.log('get success...');
    $scope.product = data.product;//console.log(data.product);
    $scope.title = $scope.product.name;
  }).error(function(data,status,headers,config){
    console.log('product get error');  
  });

  $scope.confirm_buy = function() {
    if(window.localStorage.isLogin == "false" || typeof(window.localStorage.isLogin) == "undefined"){
      window.localStorage.loginx = 'topay';
      $state.go('product-login',{p:'topay'});
    } else {
      $state.go('pay-index',{id:$scope.product.id});
    }
  };

})

.controller('CounselController', function($scope, $location, $ionicPlatform, $ionicNavBarDelegate) {
  $scope.next = function() {
    $location.path('/counsel/tzfx');
  };

  //主页面显示退出提示框
  $ionicPlatform.registerBackButtonAction(function (e) {
    e.preventDefault();
    function showConfirm() {
      var confirmPopup = $ionicPopup.confirm({
        title: '<strong>退出?</strong>',
        template: '你确定要退出吗?',
        okText: '退出',
        cancelText: '取消'
      });
      confirmPopup.then(function (res) {
        if (res) {
          ionic.Platform.exitApp();
        } else {
          // Don't close
        }
      });
    }
    // Is there a page to go back to?
    if ($location.path() == '/web/counsel/index' ) {
      showConfirm();
    } else if ($rootScope.$viewHistory.backView ) {
      console.log('currentView:', $rootScope.$viewHistory.currentView);
      // Go back in history
      $rootScope.$viewHistory.backView.go();
    } else {
      // This is the last page: Show confirmation popup
      showConfirm();
    }
    return false;
  }, 101);

})

/* 投资分析提交 @alexlee */
.controller('TzfxController', function($scope, $state, $http, $q, $ionicLoading, $ionicHistory, $httpParamSerializer,$cordovaFileTransfer,$timeout,$ionicPopup,tzxfService) {

  //跳转
  var totzfx = window.localStorage.loginx;
  if (totzfx == "totzfx"){
    window.localStorage.removeItem('loginx');
  }

  $scope.counsel_product_detail = function() {
    $state.go('counsel-product-detail');
  };

  $scope.tzfxData = tzxfService.get();
  console.log($scope.tzfxData);


  $scope.counsel_ptype = function() {
    $state.go('counsel-tzfx-ptype');
  };

  $scope.backtzfxptype = function(){
    //$scope.tzfxData.ptype = tzfxData.ptype;
    tzxfService.set($scope.tzfxData);
    $state.go('counsel-tzfx',{}); 
  };  

  function checknext(){/*
    if(!$scope.tzfxData.project){
      inf='请填写项目名称';
      return false;
    }*/
    if(!$scope.tzfxData.ptype){
      inf='请选择产品类型';
      return false;
    }
    if(!$scope.tzfxData.amount){
      inf='请填写投资额度';
      return false;
    }
    if(!$scope.tzfxData.deadline){
      inf='请填写投资期限-天数';
      return false;
    }
    return true;
  }
  $scope.imgnums = 0;
  var saveimgs = $scope.tzfxData.imgs
  if(angular.isArray(saveimgs)){  
    $scope.imgnums = saveimgs.length;
  }

  $scope.submittzfx = function() {
    if(!$scope.tzfxData.intro){
      $ionicPopup.alert({title: '请到产品详情填写详细描述！', okText:'确定'});
      return false;
    }
    tzxfService.set($scope.tzfxData);
    if(window.localStorage.isLogin == 'true'){
      //(window.localStorage.isLogin == "false" || typeof(window.localStorage.isLogin) == "undefined")

      $scope.tzfxData.memberId = window.localStorage.memberId;
      //$scope.tzfxData.aname=window.localStorage.aname;
      //$scope.tzfxData.phone = window.localStorage.phone;
      //$scope.tzfxData.email=window.localStorage.email;        
      //$scope.tzfxData.qq=window.localStorage.qq;
      console.log($scope.tzfxData);
      if(checknext()){ 
        $scope.uploadedids=[];
        if($scope.imgnums>0){
          sendImg(saveimgs).then(function(res){
            //第一步 上传图片 获取文件id         
            //第二步 文件id参数 赋给 attachment_ids
            angular.forEach(res, function(value) {
              var res= angular.fromJson(value); //字符串数组 非json
              $scope.uploadedids.push(res.id);
            });
            console.log($scope.uploadedids);
            $ionicLoading.hide(); 
            $scope.tzfxData.attachmentIds = $scope.uploadedids.join(',');
            console.log($scope.tzfxData);
            sendTzfxData($scope.tzfxData);        
          });
        }else{
          sendTzfxData($scope.tzfxData);
        }
      }else{
        $ionicPopup.alert({title: inf, okText:'确定'});
      }      
    }
    else{
      window.localStorage.loginx = 'totzfx';
      $state.go('counsel-login',{p:'totzfx'});
    } 
  };  //end submittzfx  
    
  function sendTzfxData(data){
    $ionicLoading.show({template: '<ion-spinner class="light"></ion-spinner>'});
    $http.post(window.localStorage.base_url+'/app/tzfx/post?'+$httpParamSerializer(data))
    .success(function(req){
      $ionicLoading.hide();
      if(req.code=='0'){
        console.log(req); 
        tzxfService.set(null);//清空保存数据
        $ionicPopup.alert({title:'提交成功',okText:'确定'}).then(function(){
          $state.go('web.counsel-index');
        });  
      }else{
        console.log(req);
        $ionicPopup.alert({title: req.msg, okText:'确定'});
      }
    }).error(function(res){
      $ionicLoading.hide();
      console.log(res);
    });
  }

  function sendImg(imgs){
    //$scope.sends = 0;
    $ionicLoading.show({template: '<ion-spinner class="light"></ion-spinner>'});
    //$scope.sends+'/'+$scope.imgnums+
    var promises = imgs.map(function(img) {
      //return $q.when(uploadFile(img));//promise
      return uploadFile(img);//promise
    });
    return $q.all(promises);
  }

  function sendImgb(imgs){
    //$scope.sends = 0;
    $ionicLoading.show({template: '<ion-spinner class="light"></ion-spinner>'});
    var promises = [];
    angular.forEach(imgs , function(img) {
        var promise = uploadFile(img);
        promises.push(promise);
    });
    return $q.all(promises);       
  }

  function uploadFile(fileURL) {
    var deferred = $q.defer();
    var promise = deferred.promise;
    //imageURI=fileURL
    var uri = encodeURI(window.localStorage.base_url+"/app/attachment/upload");

    var filename = fileURL.substr(fileURL.lastIndexOf('/') + 1);
    filename.indexOf('?')>=0 ? filename=filename.substr(filename.indexOf('?')+1,filename.length)+'.jpg' : '';
    var options = new FileUploadOptions();
    options.fileKey = "file";
    options.fileName = filename;
    options.mimeType = "image/jpeg";
    //options.params = {'directory':'upload', 'fileName':filename} 
    //var headers={'headerParam':'headerValue'};
    //options.headers = headers;

    /*var ft = new FileTransfer();
    ft.onprogress = function(progressEvent) {
        if (progressEvent.lengthComputable) {
          loadingStatus.setPercentage(progressEvent.loaded / progressEvent.total);
        } else {
          loadingStatus.increment();
        }
    };
    ft.upload(fileURL, uri, 
      function(r){
        console.log("Code = " + r.responseCode);
        console.log("Response = " + r.response);
        console.log("Sent = " + r.bytesSent);
        var res=r.response;     
        //$scope.uploadedfiles.push(res.id);/////?????  wrong
        //dfd.resolve(res.id);   /// wrong
        dfd.resolve(res.response);
      },
      function(error){
        console.log("An error has occurred: Code = " + error.code);
        console.log("upload error source " + error.source);
        console.log("upload error target " + error.target);
      },
      options);

    return dfd.promise;*/
    document.addEventListener('deviceready', function () {
      $cordovaFileTransfer.upload(uri, fileURL, options)
        .then(function(result) {
          console.log("Code = " + result.responseCode);
          console.log("Response = " + result.response);
          console.log("Sent = " + result.bytesSent);
          //$scope.sends++;
          deferred.resolve(result.response);
          console.log("SUCCESS: " + JSON.stringify(result)); // Success!
          //$ionicPopup.alert({title:res.id,okText:'确定'});
        }, function(err) {
          deferred.reject(err);
          console.log("ERROR: " + JSON.stringify(err));// Error
          $ionicPopup.alert({title:err+fileURL,okText:'确定'});      
          
        }, function (progress) {
          // constant progress updates
        }); 
    }, false);
    return promise;  
  }
   
})

/* 投资分析--产品详情 @alexlee */
.controller('TzfxPdetailController', function($scope, $location,$ionicPopup, $ionicLoading,$ionicActionSheet, $timeout, $cordovaCamera, tzxfService, _) {

  $scope.tzfxPdetailData = {};
  var tzfxDatas = tzxfService.get();
  if(tzfxDatas.intro != undefined)
    $scope.tzfxPdetailData.intro = tzfxDatas.intro;

  //submit txfxDatas
  $scope.myGoback = function() {      
    tzfxDatas.intro = $scope.tzfxPdetailData.intro;      
    tzfxDatas.imgs = $scope.images_list;     
    tzxfService.set(tzfxDatas);
    $location.path('/counsel/tzfx');  
  };

  //选择选择图片 
  //$scope.images_list = [];
  //var img = ['img/adam.jpg','img/max.png','img/ben.png','img/mike.png','img/perry.png'];
  $scope.images_list = [];
  var imgsave = tzfxDatas.imgs;
  if(angular.isArray(imgsave)){
    $scope.images_list = imgsave;
  }
  $scope.imgnums = $scope.images_list.length;
  $scope.imgscrollw = $scope.images_list.length*160;  
  $scope.imgscrollt = $scope.images_list.length*100;
  $scope.delimg = function(img){
    var imgs = _.filter($scope.images_list, function(item){ return item!= img; });
    //var imgs = _.filter([2], function(item){ return item!= 2; });
    $scope.images_list = imgs;
    //console.log(imgs)
    $scope.imgnums = $scope.images_list.length;
    $scope.imgscrollw = $scope.images_list.length*160;
    $scope.imgscrollt = $scope.images_list.length*100;
  }

  // "选择拍照或上传图片"  
  $scope.choosePicMenu = function() {  
    $ionicActionSheet.show({
      titleText: '请选择',
      buttons: [
        { text: '<i class="icon ion-camera lanse"></i><a class="lanse">选择拍照</a>' },
        { text: '<i class="icon ion-images lanse"></i><a class="lanse">从手机相册选择</a>' }
      ],

      cancelText: '<i class="icon ion-android-exit assertive"></i><a class="lanse">取消</a>',
      cancel: function() {
        console.log('CANCELLED');//return true;
      }, 
      buttonClicked: function(index) {
        switch (index){
          case 0: byCamera();//picFrom('Camera.PictureSourceType.CAMERA');
            break;
          case 1: pickImage();//picFrom('Camera.PictureSourceType.PHOTOLIBRARY');
            break;  
          default: break;  
        }      
        return true;  
      }
    });
  }

  var picFrom = function (stype) {
    //popsth();
    var options = {
        quality: 80,
        destinationType: Camera.DestinationType.FILE_URI,
        sourceType: stype,
        targetWidth: 800,
        targetHeight: 800
    };

    $cordovaCamera.getPicture(options).then(function(imageUri) {
        console.log(imageUri);
        $scope.images_list.push(imageUri);
                
    }, function(err) {
    // error
    });
  }
  var byCamera = function () {
        var options = {
            quality: 80,
            destinationType: Camera.DestinationType.FILE_URI,
            sourceType: Camera.PictureSourceType.CAMERA,
            targetWidth: 800,
            targetHeight: 800
        };

        $cordovaCamera.getPicture(options).then(function(imageUri) {
            console.log(imageUri);
            $scope.images_list.push(imageUri);
            $scope.imgnums = $scope.images_list.length;
            $scope.imgscrollw = $scope.images_list.length*160;
        $scope.imgscrollt = $scope.images_list.length*100;
                    
        }, function(err) {
        // error
        });
      };

  var pickImage = function () {
        var options = {
            quality: 80,
            destinationType: Camera.DestinationType.FILE_URI,
            sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
            targetWidth: 800,
            targetHeight: 800
        };

        $cordovaCamera.getPicture(options).then(function(imageUri) {
            console.log(imageUri);//rename file modified?jpg
            $scope.images_list.push(imageUri);console.log($scope.images_list);
            $scope.imgnums = $scope.images_list.length;
            $scope.imgscrollw = $scope.images_list.length*160;
            $scope.imgscrollt = $scope.images_list.length*100;
                    
        }, function(err) {
        // error
        });
      };

})

/* 法律咨询--详情 @alexlee */
.controller('lawDataController', function($scope, $location,$ionicPopup, $ionicLoading,$ionicActionSheet, $timeout, $cordovaCamera, lawService, _) {

  $scope.lawData = {};
  var lawDatas = lawService.get();
  if(lawDatas.lawcontent != undefined)
    $scope.lawData.lawcontent = lawDatas.lawcontent;
 
  $scope.backlawdata = function() {      
    lawDatas.lawcontent = $scope.lawData.lawcontent;      
    lawDatas.imgs = $scope.images_list;     
    lawService.set(lawDatas);
    $location.path('/counsel/law');  
  };

  //选择选择图片 
  $scope.images_list = [];
  var imgsave = lawDatas.imgs;//undefined false
  if(angular.isArray(imgsave)){
    $scope.images_list = imgsave;
  }
  $scope.imgnums = $scope.images_list.length;
  $scope.imgscrollw = $scope.images_list.length*160;  
  $scope.imgscrollt = $scope.images_list.length*100;
  $scope.delimg = function(img){
    var imgs = _.filter($scope.images_list, function(item){ return item!= img; });
    //var imgs = _.filter([2], function(item){ return item!= 2; });
    $scope.images_list = imgs;
    //console.log(imgs)
    $scope.imgnums = $scope.images_list.length;
    $scope.imgscrollw = $scope.images_list.length*160;
    $scope.imgscrollt = $scope.images_list.length*100;
  }

  // "选择拍照或上传图片"  
  $scope.choosePicMenu = function() {  
    $ionicActionSheet.show({
      titleText: '请选择',
      buttons: [
        { text: '<i class="icon ion-camera lanse"></i><a class="lanse">选择拍照</a>' },
        { text: '<i class="icon ion-images lanse"></i><a class="lanse">从手机相册选择</a>' }
      ],

      cancelText: '<i class="icon ion-android-exit assertive"></i><a class="lanse">取消</a>',
      cancel: function() {
        console.log('CANCELLED');//return true;
      }, 
      buttonClicked: function(index) {
        switch (index){
          case 0: byCamera();//picFrom('Camera.PictureSourceType.CAMERA');
            break;
          case 1: pickImage();//picFrom('Camera.PictureSourceType.PHOTOLIBRARY');
            break;  
          default: break;  
        }      
        return true;  
      }
    });
  }

  var picFrom = function (stype) {
    //popsth();
    var options = {
        quality: 80,
        destinationType: Camera.DestinationType.FILE_URI,
        sourceType: stype,
        targetWidth: 800,
        targetHeight: 800
    };

    $cordovaCamera.getPicture(options).then(function(imageUri) {
        console.log(imageUri);
        $scope.images_list.push(imageUri);
                
    }, function(err) {
    // error
    });
  }
  var byCamera = function () {
        var options = {
            quality: 80,
            destinationType: Camera.DestinationType.FILE_URI,
            sourceType: Camera.PictureSourceType.CAMERA,
            targetWidth: 800,
            targetHeight: 800
        };

        $cordovaCamera.getPicture(options).then(function(imageUri) {
            console.log(imageUri);
            $scope.images_list.push(imageUri);
            $scope.imgnums = $scope.images_list.length;
            $scope.imgscrollw = $scope.images_list.length*160;
        $scope.imgscrollt = $scope.images_list.length*100;
                    
        }, function(err) {
        // error
        });
      };

  var pickImage = function () {
        var options = {
            quality: 80,
            destinationType: Camera.DestinationType.FILE_URI,
            sourceType: Camera.PictureSourceType.PHOTOLIBRARY,
            targetWidth: 800,
            targetHeight: 800
        };

        $cordovaCamera.getPicture(options).then(function(imageUri) {
            console.log(imageUri);//rename file modified?jpg
            $scope.images_list.push(imageUri);console.log($scope.images_list);
            $scope.imgnums = $scope.images_list.length;
            $scope.imgscrollw = $scope.images_list.length*160;
            $scope.imgscrollt = $scope.images_list.length*100;
                    
        }, function(err) {
        // error
        });
      };

})

/* li @alexlee */
.controller('LcghController', function($scope, $state, $http, $ionicLoading, $httpParamSerializer,$location, $ionicHistory, $timeout,$ionicPopup,lcghService) {
  //lcgh10
  $scope.state = {}
  function setstate(state){
    switch(state){
      case '0':
        $scope.state.ones = true;
        $scope.state.twos = false;
        $scope.state.threes = false;
        break;//
      case '1':
        $scope.state.ones = false;
        $scope.state.twos = true;
        $scope.state.threes = false;
        break;//
      case '2':
        $scope.state.ones = false;
        $scope.state.twos = false;
        $scope.state.threes = true;
        break;//
    }
  }
    
  if(window.localStorage.lcgh10state){
    switch(window.localStorage.lcgh10state){
      case 'a':
        setstate('0');
        break;//
      case 'b':
        setstate('1'); 
        break;//
      case 'c':
        setstate('2');
        break;//
    }
  }else{
    setstate('0');
  } 
  
  $scope.one = function(){
    setstate('0'); 
    window.localStorage.lcgh10state = 'a';
  };
  $scope.two = function(){
    setstate('1'); 
    window.localStorage.lcgh10state = 'b';
  };
  $scope.three = function(){
    setstate('2'); 
    window.localStorage.lcgh10state = 'c';
  };


  //登录跳转/counsel/lcgh10
  var logintolcgx = window.localStorage.loginx;
  if (logintolcgx == "tolcgh"){
    window.localStorage.removeItem('loginx');
  }

  $scope.lcghData = {};
  var lcghDatas = lcghService.get();
  $scope.lcghData = lcghDatas;

  $scope.myGoback = function() {     
    lcghService.set($scope.lcghData);
    $state.go('counsel-lcgh'); 
  };
  $scope.myGoback1 = function() {     
    lcghService.set($scope.lcghData);
    $state.go('counsel-lcgh1'); 
  };
  $scope.myGoback2 = function() {     
    lcghService.set($scope.lcghData);
    $state.go('counsel-lcgh2'); 
  };
  $scope.myGoback3 = function() {     
    lcghService.set($scope.lcghData);
    $state.go('counsel-lcgh3'); 
  };
  $scope.myGoback4 = function() {     
    lcghService.set($scope.lcghData);
    $state.go('counsel-lcgh4'); 
  };
  $scope.myGoback5 = function() {     
    lcghService.set($scope.lcghData);
    $state.go('counsel-lcgh5'); 
  };
  $scope.myGoback6 = function() {     
    lcghService.set($scope.lcghData);
    $state.go('counsel-lcgh6'); 
  };
  $scope.myGoback7 = function() {     
    lcghService.set($scope.lcghData);
    $state.go('counsel-lcgh7'); 
  };
  $scope.myGoback8 = function() {     
    lcghService.set($scope.lcghData);
    $state.go('counsel-lcgh8'); 
  };
  $scope.myGoback9 = function() {     
    lcghService.set($scope.lcghData);
    $state.go('counsel-lcgh9'); 
  };

  $scope.gotolcgh2 = function(){
    lcghService.set($scope.lcghData);
    $state.go('counsel-lcgh2');
  };
  $scope.gotolcgh3 = function(){
    lcghService.set($scope.lcghData);
    $state.go('counsel-lcgh3');
  };
  $scope.gotolcgh4 = function(){
    lcghService.set($scope.lcghData);
    $state.go('counsel-lcgh4');
  };
  $scope.gotolcgh5 = function(){
    lcghService.set($scope.lcghData);
    $state.go('counsel-lcgh5');
  };
  $scope.gotolcgh6 = function(){
    lcghService.set($scope.lcghData);
    $state.go('counsel-lcgh6');
  };
  $scope.gotolcgh7 = function(){
    lcghService.set($scope.lcghData);
    $state.go('counsel-lcgh7');
  };
  $scope.gotolcgh8 = function(){
    lcghService.set($scope.lcghData);
    $state.go('counsel-lcgh8');
  };
  $scope.gotolcgh9 = function(){
    lcghService.set($scope.lcghData);
    $state.go('counsel-lcgh9');
  };
  $scope.gotolcgh10 = function(){
    lcghService.set($scope.lcghData);
    $state.go('counsel-lcgh10');
  };

  var inf='';
  function checknext(){
    if(!$scope.lcghData.s1incomeYear){
      inf = '请填写年收入';
      return false;
    };
    return true;
  }
  $scope.submitlcgh = function(){
    //lawService.set($scope.lawData);
    if(window.localStorage.isLogin == 'true'){
      //(window.localStorage.isLogin == "false" || typeof(window.localStorage.isLogin) == "undefined")
        console.log($scope.lcghData);         
        if(checknext()){
        $scope.lcghData.memberId = window.localStorage.memberId;
        $ionicLoading.show({template: '<ion-spinner class="light"></ion-spinner>'});
        $http.post(window.localStorage.base_url+'/app/jtlc/post?'+$httpParamSerializer($scope.lcghData))
        .success(function(req){
          $ionicLoading.hide();
          if(req.code=='0'){
            console.log(req);
            lcghService.set(null);//清空保存数据
            window.localStorage.removeItem('lcgh10state');
            $ionicPopup.alert({title:'提交成功',okText:'确定'}).then(function(){
              $state.go('web.counsel-index');
            });  
          }else{
            console.log(req);
            $ionicPopup.alert({title: req.msg, okText:'确定'});
          }
        }).error(function(res){
          $ionicLoading.hide();
          console.log(res);
        });

      }else{
        $ionicPopup.alert({title: inf, okText:'确定'});
      }

    }
    else{
      window.localStorage.loginx = 'tolcgh';
      $state.go('counsel-login',{p:'tolcgh'});
    } 
  };

})
/* li @alexlee */
.controller('LawController', function($scope, $state, $location, $http, $q, $httpParamSerializer, $filter,$stateParams,$timeout, $ionicPopup, $ionicLoading, $ionicHistory, $ionicViewSwitcher, $cordovaFileTransfer, lawService, _) {
  $scope.lawData = lawService.get();
  //console.log($scope.lawData);

  $scope.citys = {};
  var city2;   
  if(typeof($stateParams.city) == "undefined" && typeof($stateParams.choose) == "undefined") {    
    $scope.navdirection = true;
    for(var i=0;i<city12.length;i++){
      $scope.citys[i] = city12[i].city1;
    }
  }else{
    $scope.navdirection = false;
    for (var i = 0; i < city12.length; i++) {
      if (city12[i].city1 == $stateParams.city){
        city2 = city12[i].city2; 
        break;      
      }
    }
    for(var i=0;i<city2.length;i++){
      $scope.citys[i] = city2[i];
    }

    console.log($stateParams.city);
  }

  $scope.gocity2 = function(city1){
    if(typeof($stateParams.choose) == "undefined"){
      $scope.lawData.city1 = city1;
      lawService.set($scope.lawData);
      //$ionicViewSwitcher.nextDirection('forward');
      $state.go('counsel-law-location',{city:city1,choose:true});
    }
    else{
      $scope.lawData.city2 = city1;
      $scope.lawData.choosed = true;
      lawService.set($scope.lawData);
      $ionicViewSwitcher.nextDirection('back');
      $state.go('counsel-law',{});         
    }
  }; 

  $scope.lawtype = {};
  $scope.lawtype.type1 = "刑事辩护";
  $scope.lawtype.type2 = "劳动纠纷";
  $scope.lawtype.type3 = "借贷纠纷";
  $scope.lawtype.type4 = "交通事故";
  $scope.lawtype.type5 = "合同纠纷";
  $scope.lawtype.type6 = "房产土地";
  $scope.lawtype.type7 = "婚姻继承";
  $scope.lawtype.type8 = "侵权纠纷";
  $scope.lawtype.type9 = "知识产权";
  $scope.lawtype.type10 = "人身损害";
  $scope.lawtype.type11 = "其他";
  $scope.backlawtype = function(item){
    $scope.lawData.lawtype = item;
    lawService.set($scope.lawData);
    $state.go('counsel-law',{}); 
  };    

  var inf='';
  function checknext(){
    if(!$scope.lawData.choosed){
      inf = '请选择所在城市';
      return false;
    };
    if(typeof($scope.lawData.lawtype) == 'undefined'){
      inf = '请选择事件类型';
      return false;
    };
    if(typeof($scope.lawData.lawcontent) == 'undefined'){
      //if(!$scope.lawData.lawcontent){
      inf = '咨询内容不能为空';
      //$state.go('counsel-law-data',{}); 
      return false;
    };

    return true;
  }


  $scope.imgnums = 0;
  var saveimgs = $scope.lawData.imgs
  if(angular.isArray(saveimgs)){  
    $scope.imgnums = saveimgs.length;
  }

  $scope.submitlaw = function() {

    //lawService.set($scope.lawData);
    if(window.localStorage.isLogin == 'true'){
      //(window.localStorage.isLogin == "false" || typeof(window.localStorage.isLogin) == "undefined")

      if(checknext()){
        $scope.lawsData = {};
        $scope.lawsData.memberId = window.localStorage.memberId;
        $scope.lawsData.location = $scope.lawData.city1+'-'+$scope.lawData.city2;
        $scope.lawsData.lawtype = $scope.lawData.lawtype;
        $scope.lawsData.lawcontent = $scope.lawData.lawcontent;
        //$scope.lawsData.imgs = $scope.lawData.imgs;
        console.log($scope.lawsData);

        $scope.uploadedids=[];
        if($scope.imgnums>0){
          sendImg(saveimgs).then(function(res){
            //第一步 上传图片 获取文件id         
            //第二步 文件id参数 赋给 attachment_ids
            angular.forEach(res, function(value) {
              var res= angular.fromJson(value); //字符串数组 非json
              $scope.uploadedids.push(res.id);
            });
            //console.log($scope.uploadedids);
            $ionicLoading.hide(); 
            $scope.lawsData.attachmentIds = $scope.uploadedids.join(',');
            //console.log($scope.lawsData);
            sendLawData($scope.lawsData);        
          });
        }else{
          sendLawData($scope.lawsData);
        }
      }else{
        $ionicPopup.alert({title: inf, okText:'确定'});
      }

    }else{
      window.localStorage.loginx = 'toflzx';
      $state.go('counsel-login',{p:'toflzx'});
    } 
  };

  function sendLawData(data){
    $ionicLoading.show({template: '<ion-spinner class="light"></ion-spinner>'});
    $http.post(window.localStorage.base_url+'/app/mffl/post?'+$httpParamSerializer(data))
    .success(function(req){
      $ionicLoading.hide();
      if(req.code=='0'){            
        console.log(req);
        lawService.set(null);//清空保存数据
        $ionicPopup.alert({title:'提交成功',okText:'确定'}).then(function(){
          $state.go('web.counsel-index');
        });
      }else{
        console.log(req);
        $ionicPopup.alert({title: req.msg, okText:'确定'});
      }
    }).error(function(res){
      $ionicLoading.hide();
      console.log(res);
    });
  }

  function sendImg(imgs){
    //$scope.sends = 0;
    $ionicLoading.show({template: '<ion-spinner class="light"></ion-spinner>'});
    //$scope.sends+'/'+$scope.imgnums+
    var promises = imgs.map(function(img) {
      //return $q.when(uploadFile(img));//promise
      return uploadFile(img);//promise
    });
    return $q.all(promises);
  }

  function sendImgb(imgs){
    //$scope.sends = 0;
    $ionicLoading.show({template: '<ion-spinner class="light"></ion-spinner>'});
    var promises = [];
    angular.forEach(imgs , function(img) {
        var promise = uploadFile(img);
        promises.push(promise);
    });
    return $q.all(promises);       
  }

  function uploadFile(fileURL) {
    var deferred = $q.defer();
    var promise = deferred.promise;
    //imageURI=fileURL
    var uri = encodeURI(window.localStorage.base_url+"/app/attachment/upload");

    var filename = fileURL.substr(fileURL.lastIndexOf('/') + 1);
    filename.indexOf('?')>=0 ? filename=filename.substr(filename.indexOf('?')+1,filename.length)+'.jpg' : '';
    var options = new FileUploadOptions();
    options.fileKey = "file";
    options.fileName = filename;
    options.mimeType = "image/jpeg";
    //options.params = {'directory':'upload', 'fileName':filename} 
    //var headers={'headerParam':'headerValue'};
    //options.headers = headers;
/*
    var ft = new FileTransfer();
    ft.onprogress = function(progressEvent) {
        if (progressEvent.lengthComputable) {
          loadingStatus.setPercentage(progressEvent.loaded / progressEvent.total);
        } else {
          loadingStatus.increment();
        }
    };
    ft.upload(fileURL, uri, 
      function(r){
        console.log("Code = " + r.responseCode);
        console.log("Response = " + r.response);
        console.log("Sent = " + r.bytesSent);
        var res=r.response;     
        //$scope.uploadedfiles.push(res.id);/////?????  wrong
        //dfd.resolve(res.id);   /// wrong
        deferred.resolve(r.response);
      },
      function(error){
        deferred.reject(error);
        console.log("An error has occurred: Code = " + error.code);
        console.log("upload error source " + error.source);
        console.log("upload error target " + error.target);
      },
      options);
*/
    document.addEventListener('deviceready', function () {
      $cordovaFileTransfer.upload(uri, fileURL, options)
        .then(function(result) {
          console.log("Code = " + result.responseCode);
          console.log("Response = " + result.response);
          console.log("Sent = " + result.bytesSent);
          //$scope.sends++;
          deferred.resolve(result.response);
          console.log("SUCCESS: " + JSON.stringify(result)); // Success!
          //$ionicPopup.alert({title:res.id,okText:'确定'});
        }, function(err) {
          deferred.reject(err);
          console.log("ERROR: " + JSON.stringify(err));// Error
          $ionicPopup.alert({title:err+fileURL,okText:'确定'});      
          
        }, function (progress) {
          // constant progress updates
        }); 
    }, false);
    return promise;  
  }
   
})

/* li @alexlee */
.controller('AssetController', function($scope,$stateParams,$http,$ionicLoading,$ionicPopup) {
  $scope.trade={};

  $scope.rollout=false;//活期转出
  $stateParams.action=="rollout"?$scope.rollout=true:"";

    $ionicLoading.show();
    $http.get(window.localStorage.base_url+'/app/trade/getTradeDetail?tradeId='+$stateParams.id+'&memberId='+window.localStorage.memberId+'&token='+window.localStorage.token)
    .success(function(result){
      $ionicLoading.hide();
      if(result.code=='0'){
        $scope.trade = result.trade;
      }else{
        console.log(result);
        $ionicPopup.alert({
          title: result.msg,
          okText:'确定'
          })
      }
    }).error(function(res){
      $ionicLoading.hide();
      console.log(res);
    })
})

.controller('AssetHqbController', function($scope,$http,$state,$stateParams,$ionicLoading,$ionicPopup,$ionicModal,userService,isLogin, $httpParamSerializer) {
  $scope.trade={};

  $scope.rollstate=false;//活期转出
  $stateParams.action=="rollout"?$scope.rollstate=true:"";

    $ionicLoading.show();
    $http.get(window.localStorage.base_url+'/app/trade/getTradeDetail?tradeId='+$stateParams.id+'&memberId='+window.localStorage.memberId+'&token='+window.localStorage.token)
    .success(function(result){
      $ionicLoading.hide();
      if(result.code=='0'){
        $scope.trade = result.trade; 
      }else{
        console.log(result);
        $ionicPopup.alert({
          title: result.msg,
          okText:'确定'
          })
      }
    }).error(function(res){
      $ionicLoading.hide();
      console.log(res);
    })

  $scope.rollout = function(){
    if(typeof($scope.rolldata.tradeAmount) == "undefined"){
      $ionicPopup.alert({
        title:'请填写您要转出的金额',
        okText:'确定'
      });
      return;
    }
    //交易金额 小于 起存金额
    if($scope.rolldata.tradeAmount < 1){
      $ionicPopup.alert({title:'转出金额不能少于1元',okText:'确定'});
      return;
    }
    //交易金额 大于 剩余金额
    if($scope.rolldata.tradeAmount > $scope.trade.tradeAmount){
      $ionicPopup.alert({title:'转出金额不能大于交易金额',okText:'确定'});
      return;
    }

    $scope.popuptwd = $ionicPopup.show({
      templateUrl: 'tradepwd.html',
      scope: $scope,
      cssClass: 'tradepwd'
    });/*,
      buttons: [
        { text: '取消' },
        {
          text: '确定',
          type: 'button-positive',
          onTap: function(e) {
            console.log(e);
          }
        }
      ]*/        

    $scope.popuptwd.then(function(res) {
     console.log('Tapped!', res);
    });
    $scope.showKeyBoard();


  };  
 
  $scope.tradePwd="";   
  $scope.num={"a":1,"b":2,"c":3,"d":4,"e":5,"f":6,"g":7,"h":8,"i":9,"j":0,"k":".","l":"C"};  
  $scope.doInput=function(n){    
    if ($scope.pwdlenght == 6 && n!="C") return false;    
    if(n=="C"){//清除键  
      $scope.tradePwd= $scope.tradePwd.slice(0,-1);     
    }else {
      $scope.tradePwd=$scope.tradePwd+""+n; 
    } 
        
    $scope.pwdlenght = $scope.tradePwd.length; 
  };
  var currentInput;

  $ionicModal.fromTemplateUrl('templates/pay/numberkeyboard.html', {  
    scope: $scope,
    animation: 'slide-in-up'
  }).then(function(modal) {  
    $scope.modalNumberKeyboard = modal;  
  });

  $scope.showKeyBoard=function(t){    
    $scope.modalNumberKeyboard.show();  
    var emodal = document.getElementsByClassName('keyboard')[0];
    angular.element(emodal.parentNode.parentNode).addClass('numberkeyboard');
    currentInput=t;  
  };
  $scope.finishInput=function(){  
    eval('$scope.'+currentInput+'=$scope.tradePwd==""?"0":$scope.tradePwd;');  
    $scope.modalNumberKeyboard.hide();  
  }



  $scope.shownumberkeyboard = function(){
    $scope.showKeyBoard();
  };
  $scope.canceltwd = function(){
    $scope.popuptwd.close();
    $scope.modalNumberKeyboard.hide(); 
  };
  $scope.$on('$destroy', function() {
    $scope.modalNumberKeyboard.remove();//对应删除      
  });



  $scope.rolldata = {};  
  $scope.rollmoney = function(){    
    //$scope.rolldata.tradeAmount;
    $scope.rolldata.memberId = window.localStorage.memberId;
    $scope.rolldata.token = window.localStorage.token;
    $scope.rolldata.tradeId = $scope.trade.id;
    $scope.rolldata.tradePwd = $scope.tradePwd;
    console.log($scope.rolldata);
    $ionicLoading.show();
    $http.post(window.localStorage.base_url+'/app/trade/livingTakeOut?'+$httpParamSerializer($scope.rolldata))
    .success(function(req){
      $ionicLoading.hide();
      if(req.code=='0'){
        //console.log(req); 
        $scope.tradePwd="";
        $scope.pwdlenght = 0;
        $scope.popuptwd.close();
        $scope.modalNumberKeyboard.hide();
        $state.go('user-asset-hqb',{}); //订单支付完 赠送?todo
        $ionicPopup.alert({title: req.msg,okText:'确定'}); 
      }else{
        console.log(req);
        $scope.tradePwd="";
        $scope.pwdlenght = 0;
        $scope.popuptwd.close();
        $scope.modalNumberKeyboard.hide(); 
        $ionicPopup.alert({title: req.msg,okText:'确定'});
      }
    }).error(function(res){
      $ionicLoading.hide();
      console.log(res);
    });

  };    

})
.controller('BankcardController', function($scope, $state, $location,$httpParamSerializer,$http,$ionicHistory,$ionicLoading,$ionicPopup,userService,bankcardService,$timeout) {
  $scope.isauth = false;
  userService.getUserInfo(window.localStorage.memberId).then(function(result){
    if(result.code=='0'){
      //console.log(result.member);
      $scope.isauth = result.member.isAuth=='0'?false:true; //银行卡认证返回添加银行todo
      $scope.realname = result.member.realname;
      $scope.idNumber = result.member.identityNumber;
      $scope.phoneNumber = result.member.cardPhone;
      //$scope.iscard = result.member.isCard=='0'?false:true;
      //$scope.istradepwd = result.member.isTradePwd=='0'?false:true;
    }
  },function(){
    console.log('get userinfo error');    
  });

  //console.log(window.localStorage.memberId);
  $scope.cards=[];
  function getCardList(){
    $ionicLoading.show();
    $http.get(window.localStorage.base_url+'/app/card/getCardList?memberId='+window.localStorage.memberId+'&token='+window.localStorage.token).success(function(req){
      $ionicLoading.hide();
      if(req.code=='0'){
        $scope.cards=req.cards;  //console.log($scope.cards);
        angular.forEach($scope.cards,function(value,key){          
          value.bankPingyin = eval('banklist.'+value.bankName); //增加银行对应拼音
          if (value.bankPingyin){
            value.bankpng = 'img/bank/'+value.bankPingyin+'.png';
          }else{
            value.bankpng = 'img/bank/undefined.png';
          }
        });
      }else{
        console.log(req);
        $ionicPopup.alert({
          title: req.msg,
          okText:'确定'
          })
      }
    }).error(function(res){
      $ionicLoading.hide();
      console.log(res);
    })
  }
  getCardList();

  $scope.card={
      cardNumber:'',
      bankName:'',
      realname:'',
      idNumber:'',
      phoneNumber:'',
      validateCode:'',
      memberId:window.localStorage.memberId
    };
  $scope.cardData = bankcardService.get();
  $scope.card.cardNumber = $scope.cardData.cardNumber,
  $scope.card.cardNumbershow = $scope.cardData.cardNumbershow,
  $scope.card.bankName = $scope.cardData.bankName,
  $scope.card.realname = $scope.cardData.realname,
  $scope.card.idNumber = $scope.cardData.idNumber,
  $scope.card.phoneNumber = $scope.cardData.phoneNumber,
  $scope.card.validateCode = $scope.cardData.validateCode,
  $scope.card.memberId = window.localStorage.memberId;
  $scope.backbankname = function() {
    bankcardService.set($scope.card);
    $state.go('banklist',{});
  };
  $scope.add_bankcard = function() {
    $location.path('/bankcard/add');
  };
  $scope.confirm_button = false;//防止重复提交
  $scope.confirm_addCard=function(){

    if($scope.card.bankName==''){
      $ionicPopup.alert({title: '请选择银行名称',okText:'确定'})
      return;
    }
    if($scope.card.cardNumber==''){
      $ionicPopup.alert({title: '银行卡号不能为空',okText:'确定'})
      return;
    }
    var exp = /^(\d{16}|\d{19})$/;
    if(!exp.test($scope.card.cardNumber)){
      $ionicPopup.alert({title: '银行卡号格式错误',okText:'确定'})
      return;
    }
    if($scope.card.bankName!=$scope.getbankName){
      $ionicPopup.alert({title: '银行名称卡号不匹配',okText:'确定'})
      return;
    }
    if($scope.confirm_button==true){
      return;
    }
    $scope.confirm_button = true;
    $ionicLoading.show();
    $http.post(window.localStorage.base_url+'/app/card/addCard?'+$httpParamSerializer($scope.card)+'&token='+window.localStorage.token).success(function(req){
      $ionicLoading.hide();
      if(req.code=='0'){
        $ionicPopup.alert({title:'添加成功',okText:'确定'}).then(function(){
          if(window.localStorage.paybankcardaddback = "paybankcardaddback"){            
            window.localStorage.removeItem('paybankcardaddback');
            $ionicHistory.goBack(-2);//设置后返回交易
          }else{
            $location.path('bankcard/index');
          };
        });
      }else{
        console.log(req);
        $ionicPopup.alert({
          title: req.msg,
          okText:'确定'
          })
      }
      $scope.confirm_button=false;
    }).error(function(res){
      $ionicLoading.hide()
      console.log(res);
      $scope.confirm_button=false;
    })
  }

  $scope.replace = function(){
    $scope.card.cardNumbershow = $scope.card.cardNumbershow.replace(/\s/g,'').replace(/(\d{4})(?=\d)/g,"$1 ");
    $scope.card.cardNumber = $scope.card.cardNumbershow.replace(/\s+/g,'');
  }
  
  $scope.getBankName=function(){
    var exp = /^(\d{16,19})$/;
    if(!exp.test($scope.card.cardNumber)){
      //$ionicPopup.alert({title: '银行卡号格式错误',okText:'确定'})
      return;
    }
    $http.get(window.localStorage.base_url+'/app/card/getBankName?cardNum='+$scope.card.cardNumber).success(function(req){
      if(req.code=='0'){
        $scope.getbankName=req.bankName;
      }else{
        console.log(req);
        /*$ionicPopup.alert({
          title: req.msg,
          okText:'确定'
          })*/
      }
    }).error(function(res){
      console.log(res);
    })
  }
  $scope.delCard=function(card){
    $ionicPopup.confirm({
      title:'确认删除?',
      cancelText:'取消',
      okText:'确定'
    }).then(function(res){
      if(res){
        $http.get(window.localStorage.base_url+'/app/card/delCard?cardId='+card.id+'&token='+window.localStorage.token+'&memberId='+window.localStorage.memberId).success(function(req){
          if(req.code=='0'){
            $ionicPopup.alert({title:'删除成功',okText:'确定'});
            //$location.path('bankcard/index');
            $scope.cards.splice($scope.cards.indexOf(card),1);
          }else{
            console.log(req);
            $ionicPopup.alert({
              title: req.msg,
              okText:'确定'
              })
          }
        }).error(function(res){
          console.log(res);
        })
      }
    })
  }
  $scope.fetchButton=true;
  $scope.isValidPhone=function(){
    if(/^1\d{10}$/.test($scope.card.phoneNumber)){
      $scope.fetchButton=false;
    }else{
      $scope.fetchButton=true;
    }
  }
  $scope.buttonText="获取";
  var countdown=60;
  $scope.sendCode=function(){
    $http.get(window.localStorage.base_url+'/app/card/getVerifyCode?phone='+$scope.card.phoneNumber).success(function(req){
      if(req.code=='0'){
        settime();
      }else{
        $ionicPopup.alert({
          title: req.msg,
          okText:'确定'
          })
      }
    }).error(function(res){
      console.log(res);
    })
  }
  function settime() { 
    if (countdown == 0) { 
      $scope.fetchButton=false;
      $scope.buttonText="获取"; 
      countdown = 60; 
    } else { 
      $scope.fetchButton=true;
      $scope.buttonText="重试(" + countdown + ")";
      countdown--; 
      $timeout(function() { 
      settime() 
      },1000) 
    } 
  }

})
.controller('BanklistController', function($scope,$ionicHistory,$ionicModal,bankcardService) {
  $scope.banksinfo = [
    {name: "工商银行",per: "2000",total: "2000"},
    {name: "光大银行",per: "20万",total: "无限额"},
    {name: "广发银行",per: "20万",total: "无限额"},
    {name: "华夏银行",per: "1000",total: "1000"},
    {name: "建设银行",per: "20万",total: "无限额"},
    {name: "交通银行",per: "2万",total: "2万"},
    {name: "民生银行",per: "10万",total: "无限额"},
    {name: "农业银行",per: "2万",total: "2万"},
    {name: "平安银行",per: "8000",total: "8000"},
    {name: "上海银行",per: "5000",total: "5万"},
    {name: "兴业银行",per: "10万",total: "无限额"},
    {name: "邮储银行",per: "5万",total: "5万"},
    {name: "中国银行",per: "1万",total: "1万"},
    {name: "中信银行",per: "20万",total: "无限额"},
  ];
  //'招商银行',
  $scope.banks = ['工商银行','农业银行','中国银行','建设银行','中国邮政储蓄',
  '交通银行','兴业银行','民生银行','中国光大银行',
  '华夏银行','中信银行','恒丰银行','深圳发展银行','广东发展银行',
  '上海浦东发展银行','渤海银行','浙商银行','中国农业发展银行','北京银行','宁波银行'];
  $scope.card = {};
  $scope.card = bankcardService.get();
  $scope.bankname = $scope.card.bankName;
  $scope.backbankname = function(item){
    $scope.card.bankName = item;
    bankcardService.set($scope.card);
    $ionicHistory.goBack(); 
  }; 
  $scope.supportbank = function() {
    $scope.showModal('templates/bankcard/banksupport.html');
  };
  $scope.showModal = function(templateUrl) {
    $ionicModal.fromTemplateUrl(templateUrl, {
      scope: $scope,
      animation: 'slide-in-up'
    }).then(function(modal) {
      $scope.modal = modal;
      $scope.modal.show();
    });
  }
  $scope.closeModal = function() {
    $scope.modal.hide();
    $scope.modal.remove()
  };

})
.controller('DashCtrl', function($scope) {})

.controller('ChatsCtrl', function($scope, Chats) {
  // With the new view caching in Ionic, Controllers are only called
  // when they are recreated or on app start, instead of every page change.
  // To listen for when this page is active (for example, to refresh data),
  // listen for the $ionicView.enter event:
  //
  //$scope.$on('$ionicView.enter', function(e) {
  //});

  $scope.chats = Chats.all();
  $scope.remove = function(chat) {
    Chats.remove(chat);
  };
})

.controller('ChatDetailCtrl', function($scope, $stateParams, Chats) {
  $scope.chat = Chats.get($stateParams.chatId);
})

.controller('AccountCtrl', function($scope) {
  $scope.settings = {
    enableFriends: true
  };
})
.controller('AccountCtrl', function($scope) {
  $scope.settings = {
    enableFriends: true
  };
})


.controller('UserAssetController',function($scope,$http,$stateParams,$ionicLoading,$ionicPopup,isLogin){
  isLogin.islogin();
  if(window.localStorage.isLogin == 'true'){
    $ionicLoading.show();
    $http.get(window.localStorage.base_url+'/app/assets/getPeriodAsset?memberId='+window.localStorage.memberId+'&token='+window.localStorage.token)
    .success(function(req){
      $ionicLoading.hide();
      if(req.code=='0'){
        console.log(req); //定期交易
        //总的 定期总资产periodMoney  活期总资产liveMoney  之和 总资产totalMoney
        //分的 定期交易.最新收益 + 活期交易.最新收益  之和 总最新收益
        //分的 定期交易.总收益 + 活期交易.总收益  之和 总总收益
        if (!req.lastIncome) {req.lastIncome=0};  
        $scope.assets = req;       
      }else{
        console.log(req);
        $ionicPopup.alert({title: req.msg,okText:'确定'});
      }
    }).error(function(res){
      $ionicLoading.hide();
      console.log(res);
    });
  }
  var moduleId='';
  if(window.localStorage.isLogin == 'true'){
    if($stateParams.t=='dqb'){
      $scope.title = '交易记录';//定期交易记录
      moduleId=0;
    };  
    if($stateParams.t=='hqb'){
      $scope.title = '交易记录';//灵活交易记录
      moduleId=1;
    }; 
    $ionicLoading.show();
    $http.get(window.localStorage.base_url+'/app/trade/getTradeList?memberId='+window.localStorage.memberId+'&moduleId='+moduleId+'&token='+window.localStorage.token)
    .success(function(req){
      $ionicLoading.hide();
      if(req.code=='0'){
        //console.log(req);
        $scope.tradelist = req.trades;
        $scope.tradelist.length?$scope.nolist=false:$scope.nolist=true;  
      }else{
        console.log(req);
        $ionicPopup.alert({title: req.msg,okText:'确定'});
      }
    }).error(function(res){
      $ionicLoading.hide();
      console.log(res);
    });
  }
  if(window.localStorage.isLogin == 'true'){
    $ionicLoading.show();
    $http.get(window.localStorage.base_url+'/app/trade/getPayedList?memberId='+window.localStorage.memberId+'&moduleId=0'+'&token='+window.localStorage.token)
    .success(function(req){
      $ionicLoading.hide();
      if(req.code=='0'){
        //console.log(req); 
        $scope.payedlist = req.trades;//全部交易
        $scope.payedlist.length?$scope.nolist=false:$scope.nolist=true;  
      }else{
        console.log(req);
        $ionicPopup.alert({title: req.msg,okText:'确定'});
      }
    }).error(function(res){
      $ionicLoading.hide();
      console.log(res);
    });
  }

})

.controller('UserAssetHqbController',function($scope,$http,$stateParams,$ionicLoading,$ionicPopup,$ionicModal,userService,isLogin, $httpParamSerializer){
  isLogin.islogin();
  if(window.localStorage.isLogin == 'true'){
    $ionicLoading.show();                               //getNoFixedAsset
    $http.get(window.localStorage.base_url+'/app/assets/getPeriodAsset?memberId='+window.localStorage.memberId+'&token='+window.localStorage.token)
    .success(function(req){
      $ionicLoading.hide();
      if(req.code=='0'){
        //console.log(req); //定期交易
        //总的 定期总资产periodMoney  活期总资产liveMoney  之和 总资产totalMoney
        //分的 定期交易.最新收益 + 活期交易.最新收益  之和 总最新收益
        //分的 定期交易.总收益 + 活期交易.总收益  之和 总总收益
        if (!req.lastIncome) {req.lastIncome=0};  
        $scope.assets = req;       
      }else{
        console.log(req);
        $ionicPopup.alert({title: req.msg,okText:'确定'});
      }
    }).error(function(res){
      $ionicLoading.hide();
      console.log(res);
    });
  } 
  if(window.localStorage.isLogin == 'true'){
    $ionicLoading.show();
    $http.get(window.localStorage.base_url+'/app/trade/getPayedList?memberId='+window.localStorage.memberId+'&moduleId=1&token='+window.localStorage.token)
    .success(function(req){
      $ionicLoading.hide();
      if(req.code=='0'){
        //console.log(req);
        $scope.payedlist = req.trades;
        $scope.payedlist.length?$scope.nolist=false:$scope.nolist=true;  
      }else{
        console.log(req);
        $ionicPopup.alert({title: req.msg,okText:'确定'});
      }
    }).error(function(res){
      $ionicLoading.hide();
      console.log(res);
    });
  }
})

.controller('UserAssetReturnController',function($scope,$http,$stateParams,$ionicHistory,$ionicLoading,$ionicPopup,isLogin){
  var id=$stateParams.id;
  if(window.localStorage.isLogin == 'true'){
    $ionicLoading.show();
    $http.get(window.localStorage.base_url+'/app/assets/getRefundPlanList?memberId='+window.localStorage.memberId+'&token='+window.localStorage.token)
    .success(function(req){
      $ionicLoading.hide();
      if(req.code=='0'){
        console.log(req);
        $scope.returns = req.plans;
        angular.forEach($scope.returns,function(data){
          if(id==data.id){
              $scope.detail=data;
          }
        });
      }else{
        console.log(req);
        $ionicPopup.alert({title: req.msg,okText:'确定'});
      }
    }).error(function(res){
      $ionicLoading.hide();
      console.log(res);
    });
  }
  $scope.state = {}
  function setstate(state){
    switch(state){
      case '0':
        $scope.state.ones = true;
        $scope.state.twos = false;
        $scope.state.threes = false;
        //$scope.state.fours = false;
        break;//未回款
      case '1':
        $scope.state.ones = false;
        $scope.state.twos = true;
        $scope.state.threes = false;
        //$scope.state.fours = false;
        break;//已回款
      case '2':
        $scope.state.ones = false;
        $scope.state.twos = false;
        $scope.state.threes = true;
        //$scope.state.fours = false;
        break;//回款中
      //case '3':
        //$scope.state.ones = false;
        //$scope.state.twos = false;
        //$scope.state.threes = false;
        //$scope.state.fours = true;
        //break;//回款失败
    }
  }
  setstate('0'); 
  if(window.localStorage.refundstate){
    setstate(window.localStorage.refundstate); 
    window.localStorage.removeItem('refundstate');
  }

  $scope.one = function(){
    setstate('0');
  };
  $scope.two = function(){
    setstate('1');
  };
  $scope.three = function(){
    setstate('2');
  };
  $scope.four = function(){
    setstate('3');
  };
  $scope.backtorefund = function(){
    window.localStorage.refundstate = $stateParams.state;
    $ionicHistory.goBack();
  }
})

.controller('UserAssetReturnDetailController',function($scope,$http,$stateParams,$ionicLoading,$ionicHistory,$ionicPopup,isLogin){
  var id=$stateParams.id;
  if(window.localStorage.isLogin == 'true'){
    $ionicLoading.show();
    $http.get(window.localStorage.base_url+'/app/assets/getRefundPlanDetail?id='+id+'&memberId='+window.localStorage.memberId+'&token='+window.localStorage.token)
    .success(function(req){
      $ionicLoading.hide();
      if(req.code=='0'){
        console.log(req);
        $scope.detail = req.plan;
      }else{
        console.log(req);
        $ionicPopup.alert({title: req.msg,okText:'确定'});
      }
    }).error(function(res){
      $ionicLoading.hide();
      console.log(res);
    });
  }

  $scope.backtorefund = function(){
    window.localStorage.refundstate = $stateParams.state;
    $ionicHistory.goBack();
  }
})

.controller('BankcardIndexController',function($scope,isLogin){
  isLogin.islogin();
})

.controller('feedbackController',function($scope,$state,$location,$http,$ionicLoading,$ionicPopup){

  $scope.feedback={};
  $scope.submit = function(){
    var con = $scope.feedback.content;
    if(con.length<10){
      $ionicPopup.alert({
        title: "亲，字数少了点，再写"+(10-con.length)+"个字吧",
        okText:'确定'
      });
      return false;    
    }
    if(window.localStorage.isLogin == 'true'){
      $ionicLoading.show();
      $http.post(window.localStorage.base_url+'/app/feedback/post?memberId='+window.localStorage.memberId+'&content='+$scope.feedback.content)
      .success(function(req){
        $ionicLoading.hide();
        if(req.code=='0'){
          console.log(req);
          $ionicPopup.alert({title:'提交成功',okText:'确定'}).then(function(){
              $location.path('/web/user/index');
          });
        }else{
          console.log(req);
          $ionicPopup.alert({title: req.msg,okText:'确定'});
        }
      }).error(function(res){
        $ionicLoading.hide();
        console.log(res);
      });
    }else{
      window.localStorage.loginx="tofeedback";
      $state.go('counsel-login',{p:'tofeedback'});
    }
  };


})

.controller('ConsulController',function($scope,$http,$stateParams,$ionicLoading,$ionicPopup,$ionicModal,$ionicScrollDelegate,$ionicSlideBoxDelegate,$location,userService,$timeout){
  $scope.state = {}
  function setstate(state){
    switch(state){
      case '0':
        $scope.state.ones = true;
        $scope.state.twos = false;
        $scope.state.threes = false;
        break;//
      case '1':
        $scope.state.ones = false;
        $scope.state.twos = true;
        $scope.state.threes = false;
        break;//
      case '2':
        $scope.state.ones = false;
        $scope.state.twos = false;
        $scope.state.threes = true;
        break;//
    }
  }
    
  if(window.localStorage.consulstate){
    switch(window.localStorage.consulstate){
      case 'tzfx':
        setstate('0');
        getmytzfx();
        break;//
      case 'jtlc':
        setstate('1'); 
        getmyjtlc();
        break;//
      case 'mffl':
        setstate('2');
        getmylaw();
        break;//
    }
    window.localStorage.removeItem('consulstate');
  }else{
    setstate('0');
    getmytzfx();
  }
 
  //if(window.localStorage.isLogin == 'true')

  $scope.one = function(){
    setstate('0'); 
    getmytzfx();
  };
  $scope.two = function(){
    setstate('1'); 
    getmyjtlc();
  };
  $scope.three = function(){
    setstate('2'); 
    getmylaw();
  };

  function getmytzfx(){
    $ionicLoading.show({template: '<ion-spinner class="light"></ion-spinner>'});
    $http.get(window.localStorage.base_url+'/app/tzfx/list?memberId='+window.localStorage.memberId)
    .success(function(req){
      $ionicLoading.hide();
      if(req.code=='0'){
        console.log(req); 
        $scope.tzfxlist = req.list;
        if($stateParams.id){
          angular.forEach($scope.tzfxlist,function(data){
              //console.log(data);
              if($stateParams.id==data.id){
                  $scope.tzfx=data;
              }
          });          
        }

      }else{
        console.log(req);
        $ionicPopup.alert({title: req.msg,okText:'确定'});
      }
    }).error(function(res){
      $ionicLoading.hide();
      console.log(res);
    });
  }  
  function getmyjtlc(){
    $ionicLoading.show({template: '<ion-spinner class="light"></ion-spinner>'});
    $http.get(window.localStorage.base_url+'/app/jtlc/list?memberId='+window.localStorage.memberId)
    .success(function(req){
      $ionicLoading.hide();
      if(req.code=='0'){
        console.log(req); 
        $scope.lcghlist = req.list;
        if($stateParams.id){
          angular.forEach($scope.lcghlist,function(data){
              //console.log(data);
              if($stateParams.id==data.id){
                  $scope.lcgh=data;
              }
          });          
        }

      }else{
        console.log(req);
        $ionicPopup.alert({title: req.msg,okText:'确定'});
      }
    }).error(function(res){
      $ionicLoading.hide();
      console.log(res);
    });    
  }  
  function getmylaw(){
    $ionicLoading.show({template: '<ion-spinner class="light"></ion-spinner>'});
    $http.get(window.localStorage.base_url+'/app/mffl/list?memberId='+window.localStorage.memberId)
    .success(function(req){
      $ionicLoading.hide();
      if(req.code=='0'){
        console.log(req); 
        $scope.lawlist = req.list;
        if($stateParams.id){
          angular.forEach($scope.lawlist,function(data){
              //console.log(data);
              if($stateParams.id==data.id){
                  $scope.law=data;
              }
          });          
        }

      }else{
        console.log(req);
        $ionicPopup.alert({title: req.msg,okText:'确定'});
      }
    }).error(function(res){
      $ionicLoading.hide();
      console.log(res);
    });
  }

})

.controller('ConsulDetailController',function($scope,$http,$stateParams,$ionicLoading,$ionicHistory,$ionicPopup,$ionicModal,$ionicScrollDelegate,$ionicSlideBoxDelegate,$location,userService,$timeout){

  $scope.backtomyconsul = function(){
    //console.log($stateParams.type);
    window.localStorage.consulstate = $stateParams.type;
    $ionicHistory.goBack();
  }

  if($stateParams.id && window.localStorage.isLogin == 'true'){
    
    $ionicLoading.show({template: '<ion-spinner class="light"></ion-spinner>'});
    $http.get(window.localStorage.base_url+'/app/'+$stateParams.type+'/get?memberId='+window.localStorage.memberId+'&id='+$stateParams.id)
    .success(function(req){
      $ionicLoading.hide();
      if(req.code=='0'){
        console.log(req);
        switch($stateParams.type){
          case 'tzfx':
            $scope.tzfx = req.financialConsulting;//单条记录
            $scope.title = "投资分析";
            break;
          case 'jtlc':
            $scope.lcgh = req.familyConsulting;//单条记录
            $scope.title = "理财规划";
            break;
          case 'mffl':
            $scope.law = req.lawConsulting;//单条记录
            $scope.title = "法律咨询";
            break;
        };        
      }else{
        console.log(req);
        $ionicPopup.alert({title: req.msg,okText:'确定'});
      }
    }).error(function(res){
      $ionicLoading.hide();
      console.log(res);
    });

    $scope.allImages = [];
    $ionicLoading.show({template: '<ion-spinner class="light"></ion-spinner>'});
    $http.get(window.localStorage.base_url+'/app/attachment/find?bizId='+$stateParams.id)
    .success(function(req){
      $ionicLoading.hide();
      //console.log(req);
      if(req.code=='0'){
        //$scope.imgs = req.attachments;
        angular.forEach(req.attachments,function(value){
          value.src = window.localStorage.base_url+'/app/attachment/download/'+value.id;
          //console.log(value);
          $scope.allImages.push(value);
        });
        $scope.imgnums = $scope.allImages.length;
        console.log($scope.allImages);
      }else{
        $ionicPopup.alert({title: req.msg,okText:'确定'});
      }
    }).error(function(res){
      $ionicLoading.hide();
      console.log(res);
    });
    $scope.imgnums = $scope.allImages.length;
    //$scope.allImages = [{src: 'img/perry.png'}, {src: 'img/max.png'}];     
    $scope.zoomMin = 1;

    $scope.showImages = function(index) {
      $scope.activeSlide = index;
      $scope.showModal('templates/gallery-zoomview.html');
    };
     
    $scope.showModal = function(templateUrl) {
      $ionicModal.fromTemplateUrl(templateUrl, {
        scope: $scope
      }).then(function(modal) {
        $scope.modal = modal;
        $scope.modal.show();
      });
    }
     
    $scope.closeModal = function() {
      $scope.modal.hide();
      $scope.modal.remove()
    };
     
    $scope.updateSlideStatus = function(slide) {
      var zoomFactor = $ionicScrollDelegate.$getByHandle('scrollHandle' + slide).getScrollPosition().zoom;
      if (zoomFactor == $scope.zoomMin) {
        $ionicSlideBoxDelegate.enableSlide(true);
      } else {
        $ionicSlideBoxDelegate.enableSlide(false);
      }
    };

  } 
})

.controller('VoucherController',function($scope,$http,$q,$stateParams,$ionicLoading,$ionicPopup,$location,userService,$timeout){
  $scope.discounts = [];
  function getVoucherList(){
    var deferred = $q.defer();
    $ionicLoading.show({template: '<ion-spinner class="light"></ion-spinner>'});
    var url = window.localStorage.base_url+'/app/discount/getMyDiscounts?memberId='+window.localStorage.memberId+'&state='+$stateParams.state+'&token='+window.localStorage.token;
    $http.get(url).success(function(req){
      $ionicLoading.hide();
      deferred.resolve(req);//执行成功 console.log(url);      
    }).error(function(res){
      $ionicLoading.hide();
      deferred.reject();//执行失败
      console.log(res);
    })
    return deferred.promise;
  }

  getVoucherList().then(function(result){      
    if(result.code=='0'){
        $scope.discounts=result.discounts;   console.log($scope.discounts);//undefined
      }else{
        console.log(result);
        $ionicPopup.alert({title: result.msg, okText:'确定'});
      }
  },function(){
    console.log('Discounts get error');
  });

  $scope.beenused = false;
  $scope.used = function(){
    $scope.beenused = true;
    $stateParams.state = 1;
    getVoucherList().then(function(result){      
      if(result.code=='0'){
          $scope.discounts1 = result.discounts;   console.log($scope.discounts1);//undefined
        }else{
          console.log(result);
          $ionicPopup.alert({title: result.msg, okText:'确定'});
        }
    },function(){
      console.log('Discounts get error');
    });
  }  
  $scope.unuse = function(){
    $scope.beenused = false;
    $stateParams.state = 0;
    getVoucherList().then(function(result){      
      if(result.code=='0'){
          $scope.discounts1 = result.discounts;   console.log($scope.discounts1);//undefined
        }else{
          console.log(result);
          $ionicPopup.alert({title: result.msg, okText:'确定'});
        }
    },function(){
      console.log('Discounts get error');
    });
  }
});